package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QueryResource extends CoapResource {
    private static final Logger log = LoggerFactory.getLogger(QueryResource.class);

    public QueryResource(String name) {
        super(name);
        getAttributes().setTitle("Resource accepting query parameters");
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        Request request = exchange.advanced().getRequest();
        log.info("[query] req hexString:{}", Utils.toHexString(request.getBytes()));
        StringBuilder payload = new StringBuilder();
        payload.append(String.format("segPath Type: %d (%s)\nCode: %d (%s)\nMid: %d",
                request.getType().value,
                request.getType(),
                request.getCode().value,
                request.getCode(),
                request.getMID()));
        payload.append("?").append(request.getOptions().getUriQueryString());
        if (payload.length() > 64) {
            payload.delete(63, payload.length());
            payload.append('»');
        }
        exchange.respond(CoAP.ResponseCode.CONTENT, payload.toString(), MediaTypeRegistry.TEXT_PLAIN);
    }
}
